package com.example.demo.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import com.example.demo.model.UserInfo;

public interface UserRepository extends JpaRepository<UserInfo, Long>,JpaSpecificationExecutor<UserInfo> {

	@Query("from UserInfo u where u.username = ?1")
	public UserInfo getByUsername(String username);
	
	@Query("from UserInfo u where u.token = ?1")
	public UserInfo getByToken(String token);
	
	public default List<UserInfo> findSearch(String username,String token){
		
		List<UserInfo> result=findAll(new Specification<UserInfo>() {
			
			@Override
			public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();

	            if (StringUtils.isNoneBlank(username)) {
	                list.add(cb.like(root.get("username").as(String.class), "%" + username + "%"));
	            }
	            
	            Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		});
		
		return result;
	}
}
